<template>
    <div class="formDiv">
        <el-form
                ref="ruleFormRef"
                :model="ruleForm"
                :rules="rules"
                label-width="120px"
                class="demo-ruleForm"
                :size="formSize"
        >
            <el-form-item label="头像" prop="avatar" class="avatarDiv">
                <!--                <el-avatar size="large">-->
                <el-upload
                        class="avatar-uploader"
                        :auto-upload="false"
                        :on-change="getFile"
                        name="avatarFile"
                        :limit="1"
                        accept=".jpeg,.png,.jpg"
                        list-type="picture"
                        ref="uploadRef"
                        :on-preview="handlePictureCardPreview"
                >
                    <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus/>
                    </el-icon>
                </el-upload>
                <el-dialog v-model="dialogVisible">
                    <el-image  :src="dialogImageUrl" fit="fill" />
                </el-dialog>
                <!--                </el-avatar>-->
            </el-form-item>
            <el-form-item label="昵称" prop="nickname" class="avatarDiv">
                <el-input v-model="ruleForm.nickname" class="inputDiv"/>
            </el-form-item>
            <el-form-item label="电话号码" prop="phone" class="avatarDiv">
                <el-input v-model="ruleForm.phone" class="inputDiv" maxlength="11"/>
            </el-form-item>

            <el-form-item label="年龄" prop="age" class="avatarDiv">
                <el-select-v2
                        v-model="ruleForm.age"
                        placeholder="年龄"
                        :options="options"
                        class="selectDiv"
                />
            </el-form-item>

            <el-form-item label="性别" prop="sex" class="avatarDiv">
                <el-radio-group v-model="ruleForm.sex">
                    <el-radio label="男"/>
                    <el-radio label="女"/>
                </el-radio-group>
            </el-form-item>
            <el-form-item class="buttonDiv ">
                <el-button type="primary" @click="submitForm">
                    保存
                </el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>

    </div>
</template>

<script setup>
    import {reactive, ref, onMounted} from 'vue';
    import {ElMessage, ElMessageBox} from 'element-plus'
    import {Plus} from '@element-plus/icons-vue'
    import {UploadProps} from 'element-plus'
    import {UserFilled} from '@element-plus/icons-vue'
    import {useStore} from 'vuex'
    import {selectUserMessage, updateUserMessage} from "@/api/user";
    // import {selectTeacherMessage, updateTeacherMessage} from "@/api/teacher";


    const store = useStore();
    const formSize = ref('large');
    const ruleFormRef = ref();
    const uploadRef = ref();
    const dialogVisible = ref(false);
    const dialogImageUrl = ref('');

    const ruleForm = reactive({
        id: '',
        username: '',
        nickname: '',
        age: 10,
        sex: '',
        phone: '',
        avatarFile: {},
    });
    const imageUrl = ref('');
    onMounted(() => {
        selectMessage();
    })
    const handlePictureCardPreview = (uploadFile)=>{
        // console.log(uploadFile)
        dialogImageUrl.value = uploadFile.url
        dialogVisible.value = true
    }



    let nicknameTemp = '';
    let ageTemp = 10;
    let sexTemp = '';
    let phoneTemp = '';
    //获取原有的值333
    const selectMessage = () => {
        // if (store.getters.getStatus) {
            selectUserMessage(store.getters.getUsername).then((res) => {
                // console.log(res)
                nicknameTemp = res.data.nickname;
                // console.log("nicknameTemp"+nicknameTemp)
                ageTemp = res.data.age;
                if (res.data.sex == 'MALE') {
                    sexTemp = '男'
                } else {
                    sexTemp = '女'
                }
                phoneTemp = res.data.phone;

                ruleForm.nickname = nicknameTemp;
                ruleForm.sex = sexTemp;
                ruleForm.age = ageTemp;
                ruleForm.phone = phoneTemp;
                imageUrl.value = res.data.avatarUrl;
                ruleForm.username = store.getters.getUsername
                ruleForm.id = store.getters.getId
            })
        // }
        // if (store.getters.getTeacherStatus) {
        //     selectTeacherMessage(store.getters.getTeacherId).then((res) => {
        //         nicknameTemp = res.data.nickname;
        //         ageTemp = res.data.age;
        //         if (res.data.sex == 'MALE') {
        //             sexTemp = '男'
        //         } else {
        //             sexTemp = '女'
        //         }
        //         phoneTemp = res.data.phone;
        //
        //         ruleForm.nickname = nicknameTemp;
        //         ruleForm.sex = sexTemp;
        //         ruleForm.age = ageTemp;
        //         ruleForm.phone = phoneTemp;
        //         imageUrl.value = res.data.avatarUrl;
        //         ruleForm.username = store.getters.getTeacherStatus
        //         ruleForm.id = res.data.id
        //     })
        // }
    }
    const removeFile = () => {
        ruleForm.avatarFile = {};
    }
    //重置
    const resetForm = () => {
        ruleForm.nickname = nicknameTemp;
        ruleForm.phone = phoneTemp;
        ruleForm.age = ageTemp;
        ruleForm.sex = sexTemp;
        uploadRef.value.clearFiles();
    }
    //获取头像文件
    //on-change钩子函数
    const getFile = (rawFile) => {
        // console.log(rawFile.raw)
        ruleForm.avatarFile = rawFile.raw
        // ruleFormRef.value.validateField('course')
    }
    //提交
    const submitForm = () => {
        ruleFormRef.value.validate((valid) => {
            if (valid) {
                if (beforeAvatarUpload(ruleForm.avatarFile)) {
                    ElMessageBox.confirm(
                        '确认保存个人信息',
                        '修改个人信息',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }
                    )
                        .then(() => {
                            // ElMessage({
                            //     type: 'success',
                            //     message: 'Delete completed',
                            // })

                            if (ruleForm.sex == '男') {
                                ruleForm.sex = 'MALE'
                            } else {
                                ruleForm.sex = 'FEMALE'
                            }
                            console.log(ruleForm)
                            // if (store.getters.getStatus) {
                                updateUserMessage(ruleForm).then((res) => {
                                    store.commit("saveAvatarUrl", res.data.avatarUrl);
                                    store.commit("saveNickname", res.data.nickname)
                                    ElMessage.success("信息修改成功")
                                    setTimeout(() => {
                                        location.reload();
                                    }, 500); // 两秒后刷新页面
                                })
                            // }
                            // else if (store.getters.getTeacherStatus) {
                            //     updateTeacherMessage(ruleForm).then((res) => {
                            //         // console.log(res.data)
                            //         store.commit("saveTeacherAvatarUrl", res.data.avatarUrl);
                            //         store.commit("saveTeacherNickname", res.data.nickname);
                            //         ElMessage.success("信息修改成功")
                            //         setTimeout(() => {
                            //             location.reload();
                            //         }, 1000); // 两秒后刷新页面
                            //     })
                            // }

                        })
                        .catch(() => {
                            ElMessage({
                                type: 'info',
                                message: '取消操作',
                            })
                        })
                }

            }
        })
    }


    const rules = reactive({
        nickname: [
            {required: true, message: '请输入昵称', trigger: 'blur'},
            {pattern:/^\S+$/,message: '昵称不能有空格',trigger: 'change'}
        ],
        phone: [{required: true, message: '请输入电话号码', trigger: 'blur'},
            {min: 11, max: 11, message: '电话号码11位', trigger: 'blur'},
            {pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: "请填写正确手机号", trigger: "blur"}]
    });
    // const validatePhoneNumber =(phoneNumber)=> {
    //     // 移动手机号段：134-139、147、150-152、157-159、165、172、178、182-184、187-189、198
    //     // 联通手机号段：130-132、145、155-156、166、171、175-176、185-186、196
    //     // 电信手机号段：133、149、153-154、162、173-174、177、180-181、189、199
    //     // 虚拟运营商手机号段：170、171
    //     const regExp = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/; // 11位手机号正则表达式
    //     return regExp.test(phoneNumber);
    // }


    const options = Array.from({length: 100}).map((_, idx) => ({
        value: `${idx + 1}`,
        label: `${idx + 1}`,
    }));


    const beforeAvatarUpload = (rawFile) => {
        if (JSON.stringify(ruleForm.avatarFile) == '{}') return true
       if (rawFile.size / 1024 / 1024 > 2) {
            ElMessage.warning('头像大小不能超过2MB');
            return false;
        }
        return true;
    };
</script>

<style scoped>
    .avatar-uploader .avatar {
        width: 170px;
        height: 170px;
        display: block;
    }

    .formDiv {
        background-color: white;
        width: 80%;
        margin: 10px auto;
    }

    .avatarDiv {
        display: flex;
        align-items: baseline;
        padding-top: 10px;

    }

    .buttonDiv {
        padding-bottom: 10px;
        padding-top: 20px;
    }

    .inputDiv {
        width: 250px;
    }

    .selectDiv {
        padding-top: 20px;
    }

</style>
<style>
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>
